package com.serivice.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapper.UserMapper;
import com.properties.JwtProperties;
import com.serivice.UserService;
import com.utils.JwtUtil;
import com.vo.R;
import com.vo.po.User;
import com.vo.req.LoginDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 42
 * @date 2025/6/5
 * @Description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final StringRedisTemplate redisTemplate;

    private final JwtProperties jwtProperties;

    /**
     * 获得验证码
     * @return
     */
    @Override
    public R<Map> getCaptchaCode() {
        //1.导入hutool依赖，引入生成验证码的工具
        //2.调用工具captcha里面的CaptchaUtil包里面的createLineCaptcha方法,生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(250,40,4,5);
        lineCaptcha.setBackground(Color.LIGHT_GRAY);

        //3.获得验证码，同时需要保存到redis
        String checkCode = lineCaptcha.getCode();
        //Slf4j用的是增强，编译后会自动创建对象，再调用。
        log.info("验证码为{}",checkCode);

        //4.生成sessionId，雪花算法,方法返回类型是long，需要转化为String，不然前端会丢失
        String uuid = UUID.randomUUID().toString();


        redisTemplate.opsForValue().set("code:"+uuid,checkCode,5, TimeUnit.MINUTES);

        //5.封装，前端需要的属性，前端需要base64的编码，需要转化
        HashMap<String,String> info = new HashMap<>();
        info.put("key",uuid);
        info.put("imageData",lineCaptcha.getImageBase64());

        return R.ok(info);

    }

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @Override
    public R<Map> login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        String code = loginDTO.getCode();
        String captchaKey = loginDTO.getCaptchaKey();
        //1.非空校验
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)
                ||StringUtils.isBlank(code)||StringUtils.isBlank(captchaKey)){
            return R.error("参数错误");
        }
        //2.获得验证码
        String redisCode = redisTemplate.opsForValue().get("code:" + captchaKey);
        //3.校验验证码
        if(StringUtils.isBlank(redisCode)||!code.equals(redisCode)){
            return R.error("验证码错误");
        }

        //4.查询用户信息
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if(user==null){
            return R.error("用户不存在");
        }
        //5.校验账户密码
        if(!user.getPassword().equals(password)){
            return R.error("密码错误");
        }
        //6.下发token
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), map);
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("token",token);
        //7.响应
        return R.ok(resultMap);
    }
}
